package com.example.chapter05.database;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.example.chapter05.entity.User;

import java.util.ArrayList;
import java.util.List;

public class UserDBHelper extends SQLiteOpenHelper {
    private static final String DB_NAME = "User.db";

    private static final int DB_VERSION = 1;

    private static final String TABLE_NAME = "userInfo";

    private SQLiteDatabase mWDB = null;

    private SQLiteDatabase mRDB = null;

    private static UserDBHelper mHelper = null;

    private UserDBHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    public static UserDBHelper getInstance(Context context) {
        if (mHelper == null) {
            mHelper = new UserDBHelper(context);
        }
        return mHelper;
    }

    public SQLiteDatabase openReadLink() {
        if (mRDB == null || !mRDB.isOpen()) {
            mRDB = mHelper.getReadableDatabase();
        }
        return mRDB;
    }

    public SQLiteDatabase openWriteLink() {
        if (mWDB == null || !mWDB.isOpen()) {
            mWDB = mHelper.getWritableDatabase();
        }
        return mWDB;
    }

    public void closeLink() {
        if (mWDB != null && mWDB.isOpen()) {
            mWDB.close();
            mWDB = null;
        }

        if (mRDB != null && mRDB.isOpen()) {
            mRDB.close();
            mRDB = null;
        }
    }


    //执行创建数据库的语句
    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " ( id INTEGER  PRIMARY KEY " +
                "AUTOINCREMENT," +
                "phone VARCHAR NOT NULL,password VARCHAR NOT NULL);";
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public long insert(User user) {
        //可以用事务来解决存在的情况
        //判断当前是否存在该手机号码
        List<User> list = queryByPhone(user.getPhone());
        if (!list.isEmpty()) {
            return -1;
        }
        ContentValues values = new ContentValues();
        values.put("phone", user.getPhone());
        values.put("password", user.getPassword());
        return mWDB.insert(TABLE_NAME, null, values);
    }

    public List<User> queryByPhone(String phone) {
        List<User> list = new ArrayList<>();
        @SuppressLint("Recycle") Cursor cursor = mRDB.query(TABLE_NAME, null, "phone=?", new String[]{phone}, null,
                null,
                null);
        while (cursor.moveToNext()) {
            User user = new User();
            user.setId(cursor.getInt(0));
            user.setPhone(cursor.getString(1));
            user.setPassword(cursor.getString(2));
            list.add(user);
        }
        return list;
    }

}
